package JAVA300.第九章容器;

/**
 * 自定义一个hashmap
 * 增加泛型，结点也需要改变=NodeHash1
 */

public class TestMyHashMap03<K,V> {

    NodeHash1[] table;//位桶数组
    int size;//存放键值对个数

    public TestMyHashMap03() {
        table = new NodeHash1[16];
    }

    public void put(K key,V value){
        NodeHash1 node = new NodeHash1();
        node.hash = MyHash(key.hashCode(), table.length);
        node.key = key;
        node.value = value;
        node.next = null;

        //插入节点
        NodeHash1 temp = table[node.hash];
        NodeHash1 iterNode = null;//用来保存遍历时链表最后一个
        if (temp == null){
            table[node.hash] = node;
            size++;
        }else{

            while (temp!=null){//要不断迭代判断

                //判断是否有key重复，重复就要覆盖操作
                if (temp.key.equals(node.key)){
                    //cover,key next都不变 所以直接改value就ok

                    temp.value = (V)value;
                    return;
                }else {
                    iterNode = temp;
                    temp = temp.next;

                }

            }

            iterNode.next = node;
            size++;


        }


    }

    public V get(K key){

        int hash = MyHash(key.hashCode(), table.length);
        Object getResult = null;

        if (table[hash] != null){

            NodeHash1 temp = table[hash];

            while (temp != null){
                if (temp.key.equals(key)){
                    getResult = temp.value;
                    return (V) getResult;
                }else {
                    temp = temp.next;
                }

            }
        }
        return (V) getResult;
    }

    public int MyHash(int v,int length){
      //  System.out.println("hash:"+(v&(length-1)));
        return v&(length-1);
    }

    @Override
    public String toString() {
        //result:{10:aa,20:bb}
        StringBuilder sb = new StringBuilder();
        sb.append('{');

        //遍历bucket数组
        for (int i=0;i< table.length;i++){
             NodeHash1 temp = table[i];

             //遍历链表

             while (temp != null){
                 sb.append(temp.key +":"+temp.value);
                 temp = temp.next;
             }
        }

        sb.append('}');

        return sb.toString();
    }

    public static void main(String[] args) {
        TestMyHashMap03<Integer,String> myhashMap = new TestMyHashMap03<>();
        myhashMap.put(10,"aa");


        //myhashMap.put(86,"zz");


        System.out.println(myhashMap);
    }
}
